import { useMemberStore } from '@/stores/modules/member'

// 拦截下请求后拼接前缀
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

// 添加请求拦截器
const httpInterceptor = {
        // 拦截前触发
        invoke(options: UniApp.RequestOptions) {
                // 1、非http开头的接口url需要拼接地址
                if (!options.url.startsWith('http')) {
                        options.url = baseURL + options.url
                }
                // 2、设置请求超时时间10s(默认单位为毫秒)
                options.timeout = 10000
                // 3、添加小程序的请求头标识
                options.header = {
                        ...options.header,
                        // 做标记，方便后端识别接口请求来自于哪个端
                        'source-client': 'miniapp'
                }
                // 4、添加token请求头标识(从pinia中获取)
                const memberStore = useMemberStore()
                const token = memberStore.profile?.token
                if (token) {
                        options.header.Authorization = token
                }
        }
}
// 请求拦截器
uni.addInterceptor('request', httpInterceptor)
// 上传文件拦截器
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
        code: string,
        msg: string,
        result: T
}
export const getAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'GET'
        return new Promise<Data<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        // 接口有响应
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail: (error) => {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}
interface Data2<T> {
        access_token: string
        expires_in: number
        refresh_token: string
        scope: string
        session_key: string
        session_secret: string
}
interface Data3<T> {
        city: string
        city_code: string
        county: string
        county_code: string
        detail: string
        lat: any
        lng: any
        log_id: bigint
        person: string
        phonenum: string
        province: string
        province_code: string
        text: string
        town: string
        town_code: string
}
export const getBaiduApiAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'GET'
        return new Promise<Data2<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        // 接口有响应
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data2<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail: (error) => {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}
export const postAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'POST'
        return new Promise<Data<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail(error) {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}
export const postBaiduApiAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'POST'
        return new Promise<Data3<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        // 接口有响应
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data3<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail: (error) => {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}
export const putAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'PUT'
        return new Promise<Data<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail(error) {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}

export const deleteAction = <T>(options: UniApp.RequestOptions) => {
        options.method = 'DELETE'
        return new Promise<Data<T>>((resolve, reject) => {
                uni.request({
                        ...options,
                        success: ({ data, statusCode }) => {
                                // data作为getAction的返回值
                                if (statusCode >= 200 && statusCode < 300) {
                                        // 获取数据成功，调用resolve
                                        resolve(data as Data<T>)
                                } else if (statusCode === 401) {
                                        // 401错误（token失效,清理用户信息，跳转到登录页），调用reject
                                        const memberStore = useMemberStore()
                                        memberStore.clearVipMessage()
                                        // uni.navigateTo({ url: '/pages/login/login' })
                                        reject(data)
                                } else {
                                        // 通用错误，调用reject
                                        uni.showToast({
                                                title: (data as Data<T>).msg || '请求错误',
                                                icon: 'none',
                                                mask: true
                                        })
                                }
                        },
                        // 接口没有响应
                        fail(error) {
                                // 网络错误，调用reject
                                uni.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        mask: true
                                })
                                reject(error)
                        }
                })
        })
}
